import { get } from "http";
import { Connection } from "./db/connection";
import { connectionManger } from "./db/connectionmanager";
import { mysqlTransaction } from "./db/mysqltransaction";

export async function getConnection(): Promise<any> {
    return await connectionManger.createConnection()
}


let transactionNestingLelvel = 0

/**
 * 在事务开启，事务提交和事务回滚时，先判断事务计数属性值，
 * 当事务计数属性值为1时，才进行实际事务操作
 * 嵌套的内层里面实际没有实际的事务的，只有最外层一个整体的事务的实际的事务
 */
export async function beginTransction() {
    // 开始一个事务，事务的嵌套级别加1
    ++this.transactionNestingLevel

    // 如果事务的嵌套级别为1
    if (this.transactionNestingLevel === 1) {
        // 在数据库连接上开始一个事务
        this.conn.beginTransaction()
    }
    // 如果允许嵌套事务
    else if (this.nestTransactionWithSavepoints) {
        // 创建一个保存点，保存事务的状态
        this.createSavepoint(this.getNestTransactionSavePointName())
    }
}

}export async function commitTransaciton(): Promise<void> {
    // 如果事务嵌套级别为0，则抛出noactivetransaction()异常
    if (this.transactionNestingLelvel == 0) {
        throw noactivetransaction();
    }
    // 如果只能回滚，则抛出comitfailrollbackonly()异常
    if (this.isrollbackonly) {
        throw comitfailrollbackonly();
    }
    // 如果事务嵌套级别为1，则提交事务
    if (this.transactionNestingLelvel === 1) {
        this.conn.commit();
    } 
    // 如果使用保存点进行嵌套事务，则释放保存点
    else if (this.nestTransactionWithSavepoints) {
        this.releaseSavepoint(this.getNestTransactionSavePointName());
    }
    // 事务嵌套级别减1
    --this.transactionNestingLelvel
}

export async function rollbackTransaction(){
    if(this.transactionNestingLelvel == 0){
        throw connectionexception noactivetransaction()
    }
    if(this.transactionNestingLelvel === 1){
        this.transactionNestingLelvel = 0
        this.conn.rollback()
        this.isrollbackonly = false
    }else if(this.nestTransactionWithSavepoints){
        this.rollbackToSavepoint(this.getNestTransactionSavePointName())
        --this.transactionNestingLelvel
    }else{
        this.isrollbackonly = true
        --this.transactionNestingLelvel
    }
}

export async function closeConnection() {
    return connectionManger.release()
}